<template>
  <div class="approvals-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>审批管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showSubmitDialog">
              <el-icon><Plus /></el-icon>
              提交审批
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.pending }}</div>
                <div class="stat-label">待审批</div>
              </div>
              <el-icon class="stat-icon" color="#E6A23C"><Clock /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.approved }}</div>
                <div class="stat-label">已通过</div>
              </div>
              <el-icon class="stat-icon" color="#67C23A"><Check /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.rejected }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
              <el-icon class="stat-icon" color="#F56C6C"><Close /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.highPriority }}</div>
                <div class="stat-label">高优先级</div>
              </div>
              <el-icon class="stat-icon" color="#F56C6C"><Warning /></el-icon>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="待审批" name="pending">
          <div class="tab-content">
            <div class="search-area">
              <el-form :model="searchForm" inline>
                <el-form-item label="审批类型">
                  <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
                    <el-option label="采购订单" value="purchase_order" />
                    <el-option label="库存调拨" value="transfer" />
                    <el-option label="费用报销" value="expense" />
                  </el-select>
                </el-form-item>
                <el-form-item label="优先级">
                  <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable>
                    <el-option label="高" value="high" />
                    <el-option label="中" value="medium" />
                    <el-option label="低" value="low" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="handleReset">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table :data="filteredPendingApprovals" v-loading="loading" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="typeName" label="类型" width="120" />
              <el-table-column prop="title" label="标题" width="200" />
              <el-table-column prop="content" label="内容" min-width="300" />
              <el-table-column prop="applicant" label="申请人" width="100" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row }">
                  <span v-if="row.amount > 0">¥{{ row.amount.toFixed(2) }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="100">
                <template #default="{ row }">
                  <el-tag :type="getPriorityType(row.priority)">
                    {{ getPriorityText(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="currentStep" label="进度" width="120">
                <template #default="{ row }">
                  <el-progress 
                    :percentage="(row.currentStep / row.totalSteps) * 100" 
                    :stroke-width="8"
                    :show-text="false"
                  />
                  <span class="progress-text">{{ row.currentStep }}/{{ row.totalSteps }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="申请时间" width="180" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="handleView(row)">
                    查看
                  </el-button>
                  <el-button type="success" size="small" @click="handleApprove(row)">
                    审批
                  </el-button>
                  <el-button type="danger" size="small" @click="handleReject(row)">
                    拒绝
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="已通过" name="approved">
          <div class="tab-content">
            <el-table :data="workflowStore.allApprovedItems" v-loading="loading" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="typeName" label="类型" width="120" />
              <el-table-column prop="title" label="标题" width="200" />
              <el-table-column prop="content" label="内容" min-width="300" />
              <el-table-column prop="applicant" label="申请人" width="100" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row }">
                  <span v-if="row.amount > 0">¥{{ row.amount.toFixed(2) }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="申请时间" width="180" />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="handleView(row)">
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="已拒绝" name="rejected">
          <div class="tab-content">
            <el-table :data="workflowStore.allRejectedItems" v-loading="loading" stripe>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="typeName" label="类型" width="120" />
              <el-table-column prop="title" label="标题" width="200" />
              <el-table-column prop="content" label="内容" min-width="300" />
              <el-table-column prop="applicant" label="申请人" width="100" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row }">
                  <span v-if="row.amount > 0">¥{{ row.amount.toFixed(2) }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="申请时间" width="180" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="handleView(row)">
                    查看
                  </el-button>
                  <el-button type="warning" size="small" @click="handleResubmit(row)">
                    重新提交
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 审批详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="审批详情"
      width="800px"
    >
      <div v-if="currentApproval">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审批类型">{{ currentApproval.typeName }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ currentApproval.title }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentApproval.applicant }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentApproval.createTime }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityType(currentApproval.priority)">
              {{ getPriorityText(currentApproval.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentApproval.status)">
              {{ getStatusText(currentApproval.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="内容" :span="2">{{ currentApproval.content }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>审批流程</el-divider>
        <el-timeline>
          <el-timeline-item
            v-for="(approver, index) in currentApproval.approvers"
            :key="approver.id"
            :timestamp="approver.approveTime || '待审批'"
            :type="getTimelineType(approver.status)"
          >
            <el-card>
              <h4>{{ approver.name }} ({{ approver.role }})</h4>
              <p v-if="approver.comment">{{ approver.comment }}</p>
              <el-tag :type="getApproverStatusType(approver.status)">
                {{ getApproverStatusText(approver.status) }}
              </el-tag>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 审批操作对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      :title="approvalDialogTitle"
      width="600px"
    >
      <el-form :model="approvalForm" label-width="100px">
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button 
          type="success" 
          @click="handleConfirmApprove"
          :loading="approvalLoading"
        >
          确认通过
        </el-button>
        <el-button 
          type="danger" 
          @click="handleConfirmReject"
          :loading="approvalLoading"
        >
          确认拒绝
        </el-button>
      </template>
    </el-dialog>

    <!-- 提交审批对话框 -->
    <el-dialog
      v-model="submitDialogVisible"
      title="提交审批"
      width="600px"
    >
      <el-form :model="submitForm" :rules="submitRules" ref="submitFormRef" label-width="100px">
        <el-form-item label="审批类型" prop="type">
          <el-select v-model="submitForm.type" placeholder="请选择审批类型" style="width: 100%">
            <el-option label="采购订单" value="purchase_order" />
            <el-option label="库存调拨" value="transfer" />
            <el-option label="费用报销" value="expense" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="submitForm.title" placeholder="请输入审批标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="submitForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入审批内容"
          />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="submitForm.amount"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入金额"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="submitForm.priority" placeholder="请选择优先级" style="width: 100%">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitApproval" :loading="submitLoading">
          提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'

const workflowStore = useWorkflowStore()

// 响应式数据
const loading = ref(false)
const activeTab = ref('pending')
const viewDialogVisible = ref(false)
const approvalDialogVisible = ref(false)
const submitDialogVisible = ref(false)
const approvalLoading = ref(false)
const submitLoading = ref(false)
const submitFormRef = ref()

const currentApproval = ref(null)
const approvalAction = ref('') // 'approve' 或 'reject'

// 搜索表单
const searchForm = reactive({
  type: '',
  priority: ''
})

// 审批表单
const approvalForm = reactive({
  comment: ''
})

// 提交表单
const submitForm = reactive({
  type: '',
  title: '',
  content: '',
  amount: 0,
  priority: 'medium'
})

// 表单验证规则
const submitRules = {
  type: [
    { required: true, message: '请选择审批类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入审批标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入审批内容', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 计算属性
const stats = computed(() => workflowStore.getApprovalStats())

const filteredPendingApprovals = computed(() => {
  let approvals = workflowStore.allPendingApprovals
  
  if (searchForm.type) {
    approvals = approvals.filter(item => item.type === searchForm.type)
  }
  
  if (searchForm.priority) {
    approvals = approvals.filter(item => item.priority === searchForm.priority)
  }
  
  return approvals
})

const approvalDialogTitle = computed(() => {
  return approvalAction.value === 'approve' ? '审批通过' : '审批拒绝'
})

// 方法
const handleTabChange = (tabName) => {
  activeTab.value = tabName
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleReset = () => {
  Object.assign(searchForm, {
    type: '',
    priority: ''
  })
}

const handleView = (row) => {
  currentApproval.value = row
  viewDialogVisible.value = true
}

const handleApprove = (row) => {
  currentApproval.value = row
  approvalAction.value = 'approve'
  approvalForm.comment = ''
  approvalDialogVisible.value = true
}

const handleReject = (row) => {
  currentApproval.value = row
  approvalAction.value = 'reject'
  approvalForm.comment = ''
  approvalDialogVisible.value = true
}

const handleConfirmApprove = async () => {
  if (!approvalForm.comment.trim()) {
    ElMessage.warning('请输入审批意见')
    return
  }
  
  approvalLoading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该传入实际的审批人ID，暂时使用第一个待审批的审批人
    const approver = currentApproval.value.approvers.find(ap => ap.status === 'pending')
    if (approver) {
      workflowStore.approveApproval(currentApproval.value.id, approver.id, approvalForm.comment)
      ElMessage.success('审批通过')
      approvalDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('审批失败')
  } finally {
    approvalLoading.value = false
  }
}

const handleConfirmReject = async () => {
  if (!approvalForm.comment.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  approvalLoading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const approver = currentApproval.value.approvers.find(ap => ap.status === 'pending')
    if (approver) {
      workflowStore.rejectApproval(currentApproval.value.id, approver.id, approvalForm.comment)
      ElMessage.success('审批拒绝')
      approvalDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    approvalLoading.value = false
  }
}

const handleResubmit = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重新提交该审批申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    workflowStore.resubmitApproval(row.id)
    ElMessage.success('重新提交成功')
  } catch {
    // 用户取消操作
  }
}

const showSubmitDialog = () => {
  submitDialogVisible.value = true
  resetSubmitForm()
}

const handleSubmitApproval = async () => {
  if (!submitFormRef.value) return
  
  try {
    await submitFormRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const approvalData = {
      ...submitForm,
      applicant: '当前用户', // 这里应该获取当前用户信息
      applicantId: 1,
      orderId: Date.now(),
      orderNo: `AP${Date.now()}`
    }
    
    workflowStore.submitApproval(approvalData)
    ElMessage.success('审批申请提交成功')
    submitDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetSubmitForm = () => {
  Object.assign(submitForm, {
    type: '',
    title: '',
    content: '',
    amount: 0,
    priority: 'medium'
  })
  submitFormRef.value?.clearValidate()
}

// 工具方法
const getPriorityType = (priority) => {
  const typeMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return typeMap[priority] || 'info'
}

const getPriorityText = (priority) => {
  const textMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return textMap[priority] || '中'
}

const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return textMap[status] || '未知'
}

const getTimelineType = (status) => {
  const typeMap = {
    pending: 'primary',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'primary'
}

const getApproverStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

const getApproverStatusText = (status) => {
  const textMap = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return textMap[status] || '未知'
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.approvals-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  position: relative;
  overflow: hidden;
}

.stat-card .el-card__body {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 48px;
  opacity: 0.3;
}

.tab-content {
  margin-top: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.progress-text {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}
</style>
